#!/usr/bin/python3
#coding:utf-8
from ruamel import yaml

d = [{'tasks': [{'yum': {'state': 'latest', 'name': 'httpd'}, 'name': 'ensure apache is at the latest version'},
                {'name': 'write the apache config file', 'template': {'dest': '/etc/httpd.conf', 'src': '/srv/httpd.j2'},
                 'notify': ['restart apache']}, {'name': 'ensure apache is running', 'service': {'state': 'started',
                 'name': 'httpd'}}], 'hosts': 'webservers', 'remote_user': 'root', 'vars': {'http_port': 80, 'max_clients': 200}, 'handlers': [{'name': 'restart apache', 'service': {'state': 'restarted', 'name': 'httpd'}}]}]
class YamlHandle:
    def yaml_write(url, data, default_flow_style=False):
        with open(url,"w") as f:
		    # 转为字符串，使用默认flow流格式
            yaml.dump(data,f,default_flow_style)
			# 写入文件，不是用flow流格式
            print("create yaml file success")
            return data

    def yaml_read(url):
        with open(url, 'r' encoding='utf-8') as f:
            content = yaml.load(f)
            print(content)
            return content

    def yaml_safe_read(url_file):
	    with open(url_file, 'r' encoding='utf-8') as f:  # demo.yaml内容同上例yaml字符串 
	        content = yaml.safe_load(f)
	        print(content)
            return content

	# yaml文件中含有多个文档时，分别获取文档中数据
	def get_yaml_load_all(yaml_path, yame_name):
	    yaml_file = os.path.join(yaml_path, yame_name)
		# 打开yaml文件
		file_data =  yaml_read(yaml_file)
		all_data = yaml.load_all(file_data)
		for data in all_data:
			print(data)

	def generate_yaml_doc(yaml_path, yame_name，data, default_flow_style=False):
	    yaml_file = os.path.join(yaml_path, yame_name)
		yaml_write(yaml_file, data, default_flow_style)
        print("Finish generate_yaml_doc")

	def get_yaml_data(yaml_path, yame_name):
	    yaml_file = os.path.join(yaml_path, yame_name)
		# 打开yaml文件
		print("***获取yaml文件数据***")
		file_data = yaml_read(yaml_file)
		print(file_data)
		print("类型：", type(file_data))

		# 将字符串转化为字典或列表
		print("***转化yaml数据为字典或列表***")
		data = yaml.load(file_data)
		print(data)
		print("类型：", type(data))
		return data

	def update_yml(yaml_path, save_path, data):
		with open(yaml_path, encoding="utf-8") as f:
			content = yaml.load(f, Loader=yaml.RoundTripLoader)
			# 修改yml文件中的参数
			content['service']['memo_query']['server_ip'][0] = 'mysql_host={}'.format(data)
		with open(save_path, 'w', encoding="utf-8") as nf:
			yaml.dump(content, nf, Dumper=yaml.RoundTripDumper)

if __name__ == '__main__':
    update_yml(ip_server='0.0.0.0')
